package Part2_TCP;

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * ClassName: Test1
 * Package: IntelliJ IDEA
 * Description:
 *              客户端给服务端发送文件
 *              服务端保存到本地
 * Written by HanXu
 * Create 2024.04.24 23:28
 */
public class Test1 {

    //客户端给服务端发送文件
    @Test
    public void client() throws IOException{

        //创建Socket
        InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
        Socket socket = new Socket(inetAddress,8989);


        //创建File、FileInputStream实例
        File file = new File("650.jpg");
        FileInputStream fis = new FileInputStream(file);

        //输出流
        OutputStream outputStream = socket.getOutputStream();

        //读写数据（读：读文件）（写：传数据）
        byte[] buffer = new byte[1024];
        int len;
        while ((len=fis.read(buffer))!=-1){         //读：读本地文件
            outputStream.write(buffer,0 ,len);  //写：网络传出数据
        }

        //关闭资源
        outputStream.close();
        fis.close();
        socket.close();
    }

    //服务端保存到本地
    @Test
    public void server() throws IOException {

        //创建ServerSocket
        ServerSocket serverSocket = new ServerSocket(8989);

        //接受来自于客户端的Socket
        Socket socket = serverSocket.accept();

        //通过Socket获取一个输入流
        InputStream inputStream = socket.getInputStream();

        //创建File实例、输出流存储文件
        File file = new File("650_copy.jpg");
        FileOutputStream fos = new FileOutputStream(file);

        //读写数据
        byte[] buffer = new byte[1024];
        int len;
        while ((len=inputStream.read(buffer))!=-1){ //读入传输来的数据
            fos.write(buffer,0 ,len);           //写入到本地
        }

        //关闭流、Socket、ServerSocket
        fos.close();
        inputStream.close();
        socket.close();
        serverSocket.close();
    }
}
